﻿using System;
using System.Threading;
using CSRedis;

namespace Bean.Infrastructure
{
    public class RedisQueue
    {
        public delegate void ReceivedEventHandler(object sender, ReceivedEventArgs args);

        ///队列名
        private string QueueName { get; set; }

        /// <summary>
        /// 构造方法，初始化队列名
        /// </summary>
        /// <param name="queueKey"></param>
        public RedisQueue(string queueKey, string queueName = "Queue")
        {
            QueueName = $"{queueKey}_{queueName}";
        }

        /// <summary>
        /// 获取队列的数量
        /// </summary>
        public long Count => RedisHelper.Instance.LLen(QueueName); // 获取队列长度

        /// <summary>
        /// 队列是否存在（通过检查队列是否有元素）
        /// </summary>
        public bool IsExist => Count > 0;

        /// <summary>
        /// 接收消息事件
        /// </summary>
        public event ReceivedEventHandler OnReceived;

        /// <summary>
        /// 发送消息到队列
        /// </summary>
        /// <param name="message"></param>
        public void Send(string message)
        {
            Console.WriteLine($"发送消息到队列名字：{QueueName}");
            RedisHelper.Instance.RPush(QueueName, message); // 向队列尾部添加消息
        }

        /// <summary>
        /// 从队列中出队（取出一条消息）
        /// </summary>
        /// <returns></returns>
        public string Dequeue()
        {
            return RedisHelper.Instance.LPop(QueueName); // 从队列头部弹出消息
        }

        /// <summary>
        /// 开始接收消息（在后台异步接收队列中的消息）
        /// </summary>
        public void Receive()
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    while (true)
                    {
                        try
                        {
                            // 从队列中获取消息
                            string message = Dequeue();
                            if (!string.IsNullOrEmpty(message))
                            {
                                // 触发消息接收事件
                                OnReceived?.Invoke(this, new ReceivedEventArgs { Status = 1, Message = message });
                            }
                        }
                        catch (Exception ex)
                        {
                            // 捕获异常并记录日志
                            Console.WriteLine("Receive error: " + ex.Message);
                        }
                        finally
                        {
                            // 每次尝试接收完消息后，稍作休息
                            Thread.Sleep(100);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // 捕获外部异常并触发接收事件（发送错误信息）
                    OnReceived?.Invoke(this, new ReceivedEventArgs { Status = 0, Message = ex.Message });
                }
            });
        }

        /// <summary>
        /// 移除队列（清空队列中的所有数据）
        /// </summary>
        /// <returns></returns>
        public long Remove()
        {
            return RedisHelper.Instance.Del(QueueName); // 删除整个队列
        }
    }

    // 接收消息的参数类
    public class ReceivedEventArgs : EventArgs
    {
        public int Status { get; set; } // 状态，1表示成功，0表示失败
        public string Message { get; set; } // 接收到的消息内容
    }
}